<template>
  <div class="login-bg">
    <div class="login-card">
      <h2 class="login-title">用户登录</h2>
      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="验证码登录" name="code">
          <el-form :model="form" ref="loginForm" :rules="rules" label-width="0">
            <el-row :gutter="10">
              <el-col :span="7">
                <el-select v-model="form.country" placeholder="国家" style="width: 100%">
                  <el-option label="中国" value="86" />
                  <!-- 可扩展其他国家 -->
                </el-select>
              </el-col>
              <el-col :span="17">
                <el-form-item prop="phone">
                  <el-input v-model="form.phone" maxlength="11" placeholder="请输入手机号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item prop="verify_code" class="img-code-row">
              <el-input v-model="form.verify_code" maxlength="4" placeholder="请输入图片验证码" style="width: 60%" />
              <img :src="imgCodeUrl" @click="refreshImgCode" class="img-code" :alt="'点击刷新'" />
            </el-form-item>
            <el-form-item prop="code">
              <el-row :gutter="10" style="width: 100%">
                <el-col :span="15">
                  <el-input v-model="form.code" maxlength="6" placeholder="请输入6位短信验证码" />
                </el-col>
                <el-col :span="9">
                  <el-button :disabled="smsBtnDisabled" @click="getSmsCode" style="width: 100%">{{ smsBtnText }}</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="width: 100%; background: #ff7d00; border: none;" @click="onLogin" :loading="loading">登录</el-button>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="form.remember">记住密码</el-checkbox>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <el-divider>或</el-divider>
      <el-button type="primary" icon="el-icon-link" style="width: 100%; background: #1677ff; border: none; margin-top: 10px;" @click="goDingTalk">钉钉扫码登录</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { http } from '../utils/request'
import router from "@/router/index.js";
// 简单uuid生成（如需更安全可用 uuid 包）
function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
const error = ref(false)
const errorMsg = ref('')
const activeTab = ref('code')
const loading = ref(false)
const smsBtnText = ref('获取短信验证码')
const smsBtnDisabled = ref(false)
const smsTimer = ref(null)
const smsCount = ref(60)
const form = reactive({
  country: '86',
  phone: '',
  verify_code: '',
  code: '',
  uuid: '',
  remember: false,
})
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  verify_code: [
    { required: true, message: '请输入图片验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '请输入4位验证码', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '请输入6位验证码', trigger: 'blur' },
  ],
}

const imgCodeUrl = computed(() => `http://localhost:8000/login/ImageCode/?uuid=${form.uuid}`)

function refreshImgCode() {
  form.uuid = uuidv4()
  http.get(`/login/ImageCode/?uuid=${form.uuid}`).then(res => {
    imgCodeUrl.value = res.data.img
  })
}
onMounted(() => {
  refreshImgCode()
})

function getSmsCode() {
  if (!/^1[3-9]\d{9}$/.test(form.phone)) {
    ElMessage.error('请输入正确的手机号')
    return
  }
  if (!form.verify_code || form.verify_code.length !== 4) {
    ElMessage.error('请输入4位图片验证码')
    return
  }
  smsBtnDisabled.value = true
  http.get('/login/sendcode/', { phone: form.phone })
    .then(res => {
      if (res.data.code === 200) {
        ElMessage.success('短信验证码已发送')
        startSmsTimer()
      } else {
        ElMessage.error(res.data.msg || '发送失败')
        smsBtnDisabled.value = false
        refreshImgCode()
      }
    })
    .catch(() => {
      ElMessage.error('发送失败')
      smsBtnDisabled.value = false
      refreshImgCode()
    })
}
function startSmsTimer() {
  smsCount.value = 60
  smsBtnText.value = `${smsCount.value}s后重试`
  smsBtnDisabled.value = true
  smsTimer.value = setInterval(() => {
    smsCount.value--
    smsBtnText.value = `${smsCount.value}s后重试`
    if (smsCount.value <= 0) {
      clearInterval(smsTimer.value)
      smsBtnText.value = '获取短信验证码'
      smsBtnDisabled.value = false
    }
  }, 1000)
}

function onLogin() {
  loading.value = true
  http.post('/login/login/', {
    phone: form.phone,
    code: form.code,
    verify_code: form.verify_code,
    uuid: form.uuid,
  })
    .then(res => {
      loading.value = false
      if (res.data.code === 200) {
        ElMessage.success(res.data.msg)
        // 登录成功，保存token等操作
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('userid', res.data.user)
        // 跳转首页或其他
        router.push('/')
      }else if (res.data.code === 202) {
        ElMessage.success(res.data.msg)
        // 注册成功，保存token和用户ID
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('userid', res.data.user)
        router.push('/user-info')
      } else {
        ElMessage.error(res.data.msg)
        refreshImgCode()
      }
    })
    .catch(() => {
      loading.value = false
      ElMessage.error('登录失败')
      refreshImgCode()
    })
}

function goDingTalk() {
  // 跳转到钉钉第三方登录页面
  http.get('/login/dingtalk/login/').then(res => {
    if (res.data && res.data.url) {
      window.location.href = res.data.url
    } else {
      error.value = true
      errorMsg.value = '获取钉钉登录链接失败'
      loading.value = false
    }
  })
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.login-bg::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000"><defs><radialGradient id="a" cx="50%" cy="50%"><stop offset="0%" stop-color="%23ffffff" stop-opacity="0.1"/><stop offset="100%" stop-color="%23ffffff" stop-opacity="0"/></radialGradient></defs><circle cx="200" cy="200" r="100" fill="url(%23a)"/><circle cx="800" cy="300" r="150" fill="url(%23a)"/><circle cx="400" cy="700" r="120" fill="url(%23a)"/></svg>') no-repeat center center;
  background-size: cover;
  opacity: 0.3;
}

.login-card {
  width: 450px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1), 0 8px 32px rgba(0, 0, 0, 0.08);
  padding: 48px 40px 32px 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 1;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-title {
  font-size: 32px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 8px;
  text-align: center;
  position: relative;
}

.login-title::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

.login-tabs {
  width: 100%;
  margin-top: 24px;
}

.login-tabs :deep(.el-tabs__header) {
  margin: 0 0 24px 0;
}

.login-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.login-tabs :deep(.el-tabs__active-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  color: #666;
  padding: 0 24px;
}

.login-tabs :deep(.el-tabs__item.is-active) {
  color: #667eea;
  font-weight: 600;
}

.img-code-row {
  display: flex;
  align-items: center;
}

.img-code {
  height: 40px;
  width: 100px;
  margin-left: 12px;
  border-radius: 8px;
  cursor: pointer;
  border: 2px solid #e1e5e9;
  object-fit: cover;
  transition: all 0.3s ease;
}

.img-code:hover {
  border-color: #667eea;
  transform: scale(1.05);
}

/* 美化表单元素 */
:deep(.el-input__inner) {
  border-radius: 12px;
  border: 2px solid #e1e5e9;
  padding: 12px 16px;
  font-size: 14px;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

:deep(.el-select .el-input__inner) {
  padding-right: 35px;
}

:deep(.el-button) {
  border-radius: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

:deep(.el-divider__text) {
  background: rgba(255, 255, 255, 0.95);
  color: #999;
  font-size: 14px;
}

:deep(.el-checkbox__label) {
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    width: 90%;
    margin: 20px;
    padding: 32px 24px;
  }

  .login-title {
    font-size: 28px;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-card {
  animation: fadeInUp 0.6s ease-out;
}
</style>
